package com.evil.common.log.function;

import com.evil.common.log.constant.LogConstant;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.function.Supplier;

/**
 * 日志执行时长
 *
 * @author liyang
 * @date 2022-08-08 00:00
 */
public class ExecuteTimeFunction {

    private final Logger executeTimeLogger = LoggerFactory.getLogger(LogConstant.EXECUTE_TIME_LOGGER);

    private Long start;

    private ExecuteTimeFunction() {
        this.start = System.currentTimeMillis();
    }

    public void reset() {
        start = System.currentTimeMillis();
    }

    public static ExecuteTimeFunction start() {
        return new ExecuteTimeFunction();
    }

    public static <T> T log(String type, Supplier<T> supplier) {
        ExecuteTimeFunction start = ExecuteTimeFunction.start();
        T t = supplier.get();
        start.log(type);
        return t;
    }

    public void log(String type) {
        executeTimeLogger.info("execute-time-function-name : [{}], execution-time : [{}]", type, System.currentTimeMillis() - start);
    }
}
